package com.yingyi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yingyi.service.IProductService;
import com.yingyi.domain.Product;
import com.yingyi.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@RequestMapping("/product")
@RefreshScope
public class ProductController {

    @Value("${test.name}")
    private String name;

    @Autowired
    private IProductService productService;

    @PostMapping("/add")
    @SentinelResource(value = "product-add",
            blockHandler = "addBlockHandler",
            fallback = "addFallback"
    )
    public JsonResult add(@RequestBody Product product) {
        productService.add(product);
        System.out.println(">>>>>>>>>>>>>>>name:"+name);

        return JsonResult.me();
    }

    @SentinelResource(value = "product-server-getById", blockHandler = "getByIdBlockHandler")
    @GetMapping("/getById/{id}")
    public Product getById(@PathVariable("id") Long id) {
        return new Product(id, "衣服", new BigDecimal("2231.21"), 23L);
    }

    /**
     * BlockException e 注意添加接收异常的参数
     * @param id
     * @param e
     * @return
     */
    public Product getByIdBlockHandler(@PathVariable("id") Long id, BlockException e) {
        e.printStackTrace();
        return new Product(-1L, "触发限流了", null, null);
    }
    public JsonResult addBlockHandler(@RequestBody Product product, BlockException e) {
        e.printStackTrace();
        return JsonResult.me().setMsg("触发限流了");
    }


    public JsonResult addFallback(@RequestBody Product product, Throwable throwable) {
        throwable.printStackTrace();
        return JsonResult.me().setMsg("触发熔断了");
    }
}
